
import { Component } from "react";

import Publish from './publish';

export default class Comment extends Component {
    state = {
        comments: [
            { id: 1 , content: '大家好' , time: '2022-03-23T10:46:56.200Z' },
            { id: 2 , content: '才是真的好' , time: '2022-03-23T10:46:58.100Z' },
        ]
    }
    addComment = content =>{
        let cs = this.state.comments;
        let max ;
        if( cs.length === 0 ) {
            max = 0 ;
        } else if( cs.length === 1 ) {
            max = cs[0].id ;
        } else {
            max = cs.reduce( (prev,curr) => {
                if( typeof prev === 'object' && prev !== null ) {
                    prev = prev.id ;
                }
                if( prev < curr.id ) {
                    return curr.id ;
                }
                return prev ;
            });
        }
        let arr = [ { id: max + 1 , content , time: new Date().toISOString() } , ...cs ];
        
        this.setState({
            comments: arr 
        });
    }
    render(){
        return (
            <div className="comment-wrapper">
                {/* 父组件通过 props 将自己的函数传递给子组件 */}
                <Publish add={this.addComment}></Publish>
                {
                    this.state.comments.map( c => (
                        <div className="comment" key={c.id}>
                            <p>{c.content}</p>
                            <p>{c.time}</p>
                        </div>
                    ) )
                }
            </div>
        );
    }
}